package common.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import base.model.User;
import common.utils.Contants;

public class LoginInterceptor implements HandlerInterceptor
{
		private List<String>  excludeActions;
		public List<String> getExcludeActions()
		{
			return excludeActions;
		}

		public void setExcludeActions(List<String> excludeActions)
		{
			this.excludeActions = excludeActions;
		}
		Logger Logger = LoggerFactory.getLogger(LoginInterceptor.class);
		
	    @Override
	    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	        String action = request.getRequestURI().substring(request.getContextPath().length());
	        Logger.debug(">>>:{} " + action);
	    	//	logger.info(action);
    		boolean isExclude = false;// 当前地址是否已经被添加意外？
    		if(excludeActions.contains(action))
    		{
    			isExclude = true;
    		}
    		
	        if (!isExclude) {
	            User user = (User)request.getSession().getAttribute(Contants.LOGINUSER);
	            if (user != null) isExclude = true;
	        }
	        if(isExclude)
			{
				return true;
			}
			else
			{
				request.setAttribute("msg", "您还没有登录或登录已超时，请重新登录，然后再刷新本功能！");
				response.setStatus(401);
				request.getRequestDispatcher("/login.jsp").forward(request, response);
				return false;
			}
	    }
	 
	    @Override
	    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	      
	    }

		@Override
		public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
				Exception ex) throws Exception {
			
		}
	
}
